<?php

namespace App\Http\ControllersVer1;

use Illuminate\Http\Request;

use Uuid;

use Qiniu\Auth as QiniuAuth;
use Qiniu\Storage\UploadManager;

use App\Letter;
use App\LetterPhoto;
use App\User;


class LetterController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //


    public function test() {


        return response()->json([
            'code' => 2000,
            'msg' => 'api v1 test success!'
        ]);

    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function createLetter(Request $request) {

        $this->validate($request, [
            'photo' => 'required|mimes:jpeg,png',
            'reply_to_letter_uuid' => 'string|size:32'
        ]);


        if (!$request->hasFile('photo')) {
            return response()->json([
                'code' => 4060,
                'msg' => 'no photo file'
            ]);
        }

        if (!$request->file('photo')->isValid()) {
            return response()->json([
                'code' => 4060,
                'msg' => 'photo upload is not valid.'
            ]);
        }

        //$ext = $request->file('image')->getClientOriginalExtension();

        $me = $request->user();


        $reply_to_letter = null;
        if ($request->has('reply_to_letter_uuid')) {

            $reply_to_letter_uuid = $request->input('reply_to_letter_uuid');
            $reply_to_letter = Letter::where('uuid', $reply_to_letter_uuid)->first();


            if (is_null($reply_to_letter)) {
                return response()->json([
                    'code' => 4060,
                    'msg' => 'wrong reply_to_letter_uuid.'
                ]);
            }

            if ($reply_to_letter->status == '2') {
                return response()->json([
                    'code' => 4060,
                    'msg' => 'already replied.'
                ]);
            }

            if ($reply_to_letter->receiver_id != 0 && $reply_to_letter->receiver_id != $me->id) {
                return response()->json([
                    'code' => 4060,
                    'msg' => 'you are not the receiver.'
                ]);
            }
            //
            $receiver_id = $reply_to_letter->sender_id;

        } else {
            $receiver_id = 0;
        }

        //
        $access_key = 'D5r1vUBg8Xc5UjdVYorZRdHMpvaONPrgxcyyqHxn';
        $secret_key = 'A5c7sTC7nooJCJ8YV-HOmoJFO0Wu1JuLudcWtMvF';

        $auth = new QiniuAuth($access_key, $secret_key);
        $bucket = 'xreacting';
        //todo: .env('bucket');
        $upload_token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $file_path = $request->file('photo');

        // 上传到七牛后保存的文件名
        //todo: uuid for image
        $key = str_replace('-', '', Uuid::generate(4)->string);

        // 初始化 UploadManager 对象并进行文件的上传
        $upload_mgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($upload_ret, $upload_err) = $upload_mgr->putFile($upload_token, $key, $file_path);

        if (is_null($upload_ret)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'upload image failed.'
            ]);
        }

        if ($upload_ret['key'] != $key) {
            return response()->json([
                'code' => 4060,
                'msg' => 'upload ret key is wrong'
            ]);
        }


        $letter = new Letter;
        $letter->uuid = str_replace('-', '', Uuid::generate(4)->string);
        $letter->sender_id = $me->id;
        $letter->receiver_id = $receiver_id;
        $letter->save();

        $letter_photo = new LetterPhoto;
        $letter_photo->letter_id = $letter->id;
        $letter_photo->uuid = $key;
        $letter_photo->cloud = "Qiniu";
        $letter_photo->bucket = $bucket;
        $letter_photo->save();

        //
        if (!is_null($reply_to_letter)) {
            if ($reply_to_letter->receiver_id == 0) {
                $reply_to_letter->receiver_id = $me->id;
            }
            $reply_to_letter->status = '2';
            $reply_to_letter->save();
        }

        //
        return response()->json([
            'code' => 2000,
            'msg' => 'sucesss.'
        ]);
    }


    /**
     * @param Request $request
     * @param $letter_uuid
     * @return \Illuminate\Http\JsonResponse
     */
    public function showLetter(Request $request, $letter_uuid) {

        if (strlen($letter_uuid) != 32) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong book uuid!'
            ]);
        }

        //todo?????
        $letter = Letter::where('uuid', $letter_uuid)->first();

        return response()->json([
            'code' => 2000,
            'letter' => $letter,
            'msg' => 'success!'
        ]);



    }



    /**
     * @param Request $request
     * @param $letter_uuid
     * @return \Illuminate\Http\JsonResponse
     */
    public function readLetter(Request $request) {

        $this->validate($request, [
            'letter_uuid' => 'required|string|size:32'
        ]);

        $letter_uuid = $request->input('letter_uuid');

        $letter = Letter::where('uuid', $letter_uuid)->first();

        if (is_null($letter)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong letter uuid!'
            ]);
        }

        $me = $request->user();

        if ($letter->receiver_id != $me->id) {
            return response()->json([
                'code' => 4060,
                'msg' => 'you are not the receiver.'
            ]);
        }

        if ($letter->status != '0') {
            return response()->json([
                'code' => 4060,
                'msg' => 'already read.'
            ]);

        }

        $letter->status = 1;
        $letter->save();

        return response()->json([
            'code' => 2000,
            'msg' => 'success!'
        ]);
    }

    /**
     * @param Request $request
     * @param $letter_uuid
     * @return \Illuminate\Http\JsonResponse
     */
    public function recallLetter(Request $request) {

        $this->validate($request, [
            'letter_uuid' => 'required|string|size:32'
        ]);

        $letter_uuid = $request->input('letter_uuid');

        $letter = Letter::where('uuid', $letter_uuid)->first();

        if (is_null($letter)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong letter uuid!'
            ]);
        }

        $me = $request->user();

        if ($letter->sender_id != $me->id) {
            return response()->json([
                'code' => 4060,
                'msg' => 'you are not the sender.'
            ]);
        }

        if ($letter->status == '1') {
            return response()->json([
                'code' => 4060,
                'msg' => 'already read. can not recall.'
            ]);

        } elseif ($letter->status == '2') {
            return response()->json([
                'code' => 4060,
                'msg' => 'already replied. can not recall.'
            ]);
        }

        $letter->delete();

        return response()->json([
            'code' => 2000,
            'msg' => 'success!'
        ]);



    }



    /**
     * @param Request $request
     * @param $letter_uuid
     * @return \Illuminate\Http\JsonResponse
     */
    public function passLetter(Request $request) {

        $this->validate($request, [
            'letter_uuid' => 'required|string|size:32'
        ]);

        $letter_uuid = $request->input('letter_uuid');

        $letter = Letter::where('uuid', $letter_uuid)->first();

        if (is_null($letter)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'wrong letter uuid!'
            ]);
        }

        $me = $request->user();

        if ($letter->sender_id == $me->id) {
            return response()->json([
                'code' => 4060,
                'msg' => 'you are the sender.'
            ]);
        }

        if ($letter->receiver_id != 0) {
            return response()->json([
                'code' => 4060,
                'msg' => 'the letter has receiver'
            ]);

        }

        //todo: save to passed_letters ????

        return response()->json([
            'code' => 2000,
            'msg' => 'success!'
        ]);
    }


    /**
     * @param Request $request
     */
    public function listInboxLetters(Request $request) {

        $me = $request->user();

        $letters = Letter::where([
            ['status', '<>', '2'],
            ['sender_id', $me->id],
            ['receiver_id', '<>', 0]
        ])->orWhere([
            ['status', '<>', '2'],
            ['receiver_id', $me->id]
        ])
            ->orderBy('updated_at', 'desc')
            ->take(20)
            ->get();

        return response()->json([
            'code' => 2000,
            'letters' => $letters,
            'msg' => 'sucesss.'
        ]);

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function karmaLetter(Request $request) {

        $me = $request->user();

        //todo: by gender
        $nearby_user_ids = [1,2,3,4,5,6,7,8,9,10];
        //remove me->id
        //todo:
        $passed_letter_ids = [1,2];

        //todo:
        $letter = Letter::where('status', '0')
            ->where('receiver_id', 0)
            ->where('sender_id', '<>', $me->id)
            ->whereIn('sender_id', $nearby_user_ids)
            ->whereNotIn('id', $passed_letter_ids)
            ->orderBy('updated_at', 'desc')
            ->first();

        if (is_null($letter)) {
            return response()->json([
                'code' => 4060,
                'msg' => 'no letter.'
            ]);
        }

        return response()->json([
            'code' => 2000,
            'letter' => $letter,
            'msg' => 'sucesss.'
        ]);

    }



}
